import React from 'react'
import {useState,useEffect} from "react"
import axios from 'axios'
function Shopcar() {
  let [arr,setArr] = useState([])
  let [checkall,setCHECKALL] = useState(false)
  let [sum,setsUM] = useState(0)
  useEffect(()=>{
    axios.get("/list2").then(res=>{
        setArr(res.data)
    })
  },[])
  useEffect(()=>{
    sumfn()
  },[arr])
  let addfn = (ind)=>{
        console.log(ind);
        let newarr = arr.map((item,index)=>{
            if (index == ind) {
                item.num ++
            }
            return item
        })
        setArr(newarr)

  }
 let  sumfn = ()=>{
      let sumzong = arr.reduce((a,b)=>{
          if (b.flag) {
              return a + b.price * b.num
          } else {
              return a
          }
      },0)
      setsUM(sumzong)
  }
  let del = (ind)=>{
    let newarr = arr.map((item,index)=>{
        if (index == ind) {
            item.num --
            if (item.num < 0) {
                item.num = 0
            }
        }
        return item
    })
    setArr(newarr)
  }
  let checkAll = (e)=> {
    
        setCHECKALL(e.target.checked)
        console.log(e.target.checked);
        let newARR = arr.map((item)=>{
            item.flag = e.target.checked
            return item
        })
        console.log(newARR); 
        setArr(newARR)
  }
  let chekitem = (e,index)=>{
        let newARR = arr.map((item,ind)=>{
            if (ind === index) {
                item.flag =  e.target.checked
            }
            return item
        })
        setArr(newARR)
        let ischckeall = newARR.every((item)=>item.flag)
        setCHECKALL(ischckeall)
  }
  return (
    <div>
        <p>全选：<input type="checkbox" checked={checkall} onChange={(e)=>checkAll(e)} />总价：{sum}</p>
        {
            arr && arr.length ? arr.map((item,index)=>{
                return <div key={index}>
                    <img src={item.img} alt="" />
                    <p> 商品名 ：{item.title} 价格：{item.price}</p>
                    <p> <input type="checkbox" checked={item.flag} onChange={(e)=>chekitem(e,index)}/> <button onClick={()=>del(index)}>--</button>{item.num}<button onClick={()=>addfn(index)}>++</button></p>
                </div>
            }):"暂无数据"
        }

    </div>
  )
}

export default Shopcar